package com.yhd.tomcat.handler.config;

import com.yhd.tomcat.Bootstrap;
import com.yhd.tomcat.handler.Handler;
import com.yhd.tomcat.service.BaseService;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yhd
 * @email yinhuidong1@xiaomi.com
 * @description TODO
 * @since 2021/6/10 下午3:25
 */
public class ConfigHandler extends Handler {



    private InputStream in;

    private static volatile ConfigHandler configHandler;

    private Properties webConfig;

    private ConfigHandler(){
        this.servletMap = new ConcurrentHashMap<>();
        this.in = loadConfig();
        processConfig();
    }

    /**
     * 单例模式获取配置文件处理器
     * @return
     */
    public static ConfigHandler getSingleton(){
        if (configHandler==null){
            synchronized (Bootstrap.class){
                if (configHandler==null){
                    configHandler=new ConfigHandler();
                }
            }
        }
        return configHandler;
    }

    public Map<String, BaseService> getServletMap() {
        return servletMap;
    }


    /**
     * 加载配置文件
     * @return
     */
    private InputStream loadConfig(){
        System.out.println("开始加载配置文件");
        String WEB_INF = Bootstrap.class.getResource("/").getPath();
        try {
            return new FileInputStream(WEB_INF+"web.properties");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析配置文件
     */
    private void processConfig(){
        try {
            System.out.println("开始解析配置文件");
            webConfig = new Properties();
            webConfig.load(in);
            Set<Object> objects = webConfig.keySet();
            if (!objects.isEmpty()){
                for (Object obj : objects){
                    String k =obj.toString();
                    if (k.endsWith(".url")) {
                        String servletName = k.replaceAll("\\.url$", "");
                        String url = webConfig.getProperty(k);
                        String className = webConfig.getProperty(servletName + ".className");

                        BaseService object = (BaseService) Class.forName(className).newInstance();
                        servletMap.put(url, object);

                    }
                }
            }
        } catch (Exception e) {
            System.out.println("配置文件解析失败！");
        }
    }


}
